﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using CLibArtreve.security;
using CLibArtreve.bll;
using CLibArtreve.models;

namespace WebAppArtreve.views.shared.components.users
{
    public partial class WUCRegister : System.Web.UI.UserControl
    {
        private string _connectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["ARTREVEConnectionString"].ConnectionString;
            }
        }

        private UserBLL _blladapter;
        private UserBLL BLLAdapter
        {
            get
            {
                if (_blladapter == null)
                    _blladapter = new UserBLL(_connectionString);
                return _blladapter;
            }
            set
            {
                _blladapter = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void ODSSecretQuestions_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            SecretQuestionBLL ObjectInstance = new SecretQuestionBLL(_connectionString);
            e.ObjectInstance = ObjectInstance;
        }

        protected void lnkBtnSave_Click(object sender, EventArgs e)
        {
            // Go ahead an save
            if (Page.IsValid)
            {
                // Load the profile from database, just to make sure we have recent version
                User user = new User();
                // Apply updates
                user.Firstname = txtFirstname.Text;
                user.Givenname = txtGivenname.Text;
                user.Nickname = txtNickname.Text;
                user.Dob = Convert.ToDateTime(txtDob.Text);
                user.Email = txtEmail.Text;
                user.SecretquestionId = Convert.ToInt64(ddlSecretQuestion.SelectedValue);
                user.Secretanswer = txtSecretanswer.Text;
                user.Password = Crypto.ComputeHashMD5(txtPassword.Text);

                // Save
                if (BLLAdapter.Save(user) > 0)
                {
                    txtStatus.Text = "Profile saved";
                }
                else
                {
                    txtStatus.Text = "Save failed...";
                }
            }
            else
            {
                txtStatus.Text = "Invalid data suplied.";
            }
        }
    }
}